#!/bin/sh

OPTS="defaults,noatime,errors=remount-ro"
DATA_DEV=/dev/block/userdata

SDCARD_MOUNT_POINT=/mnt/card

check_clean_dev()
{
    chkdev=$1

    chk_pattern="00000400: 0000 0000 0000 0000 0000 0000 0000 0000  ................"
    #chk_pattern="0000400 0000 0000 0000 0000 0000 0000 0000 0000"

    readstr=$(xxd -s 1024 -l 512 $chkdev | head -1)
    readstr=$(echo $readstr)

    if [ "x$chk_pattern" == "x$readstr" ]; then
        return 0
    else
        return 1
    fi
}

get_mtd_storage_type()
{
        root_dev=$(cat /proc/cmdline)
        root_dev=${root_dev#*root=}
        root_dev=${root_dev%% *}
        root_dev=${root_dev#*/dev/}
        type_path=/sys/block/$(basename ${root_dev})/device/type
        type=`cat ${type_path}`
        echo  ${type}
}

mount_data()
{
  check_clean_dev $DATA_DEV
  if [ $? -eq 0 ]; then
    echo "clean device $DATA_DEV ..."
    mke2fs -t ext4 -b 4096 -F $DATA_DEV
    mount -t ext4 -o $OPTS $DATA_DEV /userdata
  else
    mount -t ext4 -o $OPTS $DATA_DEV /userdata && umount /userdata && e2fsck -y $DATA_DEV
    echo "Mounting /userdata ..."
    mount -t ext4 -o $OPTS $DATA_DEV /userdata
    if [ $? -ne 0 ] ; then
      mke2fs -t ext4 -b 4096 -F $DATA_DEV
      mount -t ext4 -o $OPTS $DATA_DEV /userdata
    fi
  fi
}

mount_storage()
{
  mount -t ext4 -o defaults,noatime,errors=remount-ro /dev/block/userfs /storage
}

mount_storage

if `cat /proc/cmdline | grep 'mtdparts=' > /dev/null`
then
type=`get_mtd_storage_type`
echo "type is ${type}"
if [ x"${type}" == x"nor" ];then
      mount -t jffs2 $DATA_DEV /userdata
      if [ $? -ne 0 ]; then
	echo "Formating $DATA_DEV to jffs2 ..."
	flash_erase -j $DATA_DEV 0 0
	mount -t jffs2 $DATA_DEV /userdata
      fi
else
mount_data
fi
else
mount_data
fi

mkdir -p /userdata/data
ln -s /userdata/data /data

if [ ! -d "/data/tmp" ]; then
mkdir -p /data/tmp
fi
if [ ! -d "/data/dsoftbus" ]; then
mkdir -p /data/dsoftbus
fi

echo 5 > /proc/sys/vm/dirty_ratio
echo 2 > /proc/sys/vm/dirty_background_ratio
echo 100 > /proc/sys/vm/dirty_expire_centisecs
echo 100 > /proc/sys/vm/dirty_writeback_centisecs
